//
//  KATImageViewer.m
//  KATFramework
//
//  Created by Kantice on 16/4/15.
//  Copyright © 2016年 KatApp. All rights reserved.
//

#import "KATImageViewer.h"
#import "KATToast.h"



@interface KATImageViewer ()

///阴影
@property(nonatomic,retain) UIView *shadow;

///图片视图
@property(nonatomic,copy) KATImage *content;

///原始Frame
@property(nonatomic,assign) CGRect originalFrame;

///图片尺寸
@property(nonatomic,assign) CGSize imageSize;

///图片与屏幕的缩放比
@property(nonatomic,assign) float scaleRate;

///当前尺寸
@property(nonatomic,assign) CGSize currentSize;

///当前位置
@property(nonatomic,assign) CGPoint currentCenter;

///是否已经显示
@property(nonatomic,assign) BOOL isShown;

///是否为实际尺寸
@property(nonatomic,assign) BOOL isActualSize;

///是否动画中
@property(nonatomic,assign) BOOL animating;

///是否为亮色的状态栏
@property(nonatomic,assign) BOOL isLightStyleStatusBar;



///保存按钮
@property(nonatomic,retain) KATButton *saveButton;


@end



@implementation KATImageViewer

//获取实例
+ (instancetype)viewer
{
    KATImageViewer *viewer=[[[self alloc] init] autorelease];
    
    viewer.frame=CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    viewer.backgroundColor=[UIColor clearColor];
    
    viewer.shadow=[[[UIView alloc] init] autorelease];
    viewer.shadow.frame=viewer.bounds;
    viewer.shadow.backgroundColor=KCOLOR_BLACK;
    [viewer addSubview:viewer.shadow];
    
    viewer.isShown=NO;
    viewer.showDuration=0.3;
    viewer.canSave=YES;
    
    viewer.saveButton=[KATButton buttonWithFrame:CGRectMake(SCREEN_WIDTH-BUTTON_SIZE*1.5, SCREEN_HEIGHT-SCREEN_MARGIN_BOTTOM-BUTTON_SIZE*1.5, BUTTON_SIZE, BUTTON_SIZE) type:KATButtonTypeDownload color:KCOLOR_WHITE lineWidth:BUTTON_LINE scale:BUTTON_SCALE andOnClickAction:nil];
    viewer.saveButton.eventDelegate=viewer;
    viewer.saveButton.backgroundColor=KCOLOR_SHADOW;
    viewer.saveButton.layer.cornerRadius=CORNER_RADIUS;
    viewer.saveButton.clipsToBounds=YES;
    
    
    //背景点击
    UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc] initWithTarget:viewer action:@selector(hide)];
    singleTap.numberOfTapsRequired=1;//点击次数
    [viewer.shadow addGestureRecognizer:singleTap];//添加点击事件
    [singleTap release];
    
    return viewer;
}


#pragma -mark 对象方法

//显示图片
- (void)showWithImage:(KATImage *)image
{
    if(image)
    {
        if(!_isShown && !_animating)
        {
            //保存状态栏样式
            _isLightStyleStatusBar=[KATAppUtil isStatusBarLightStyle];
            
            //状态栏变亮色
            [KATAppUtil setStatusBarLightStyle];
            
            //初始化显示内容
            self.content=image;
            
            //初始化并添加手势
            _content.frame=self.bounds;
            _content.contentMode=UIViewContentModeScaleAspectFit;
            _content.userInteractionEnabled=YES;
            [self addSubview:_content];
            
            
            UITapGestureRecognizer *singleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)];
            singleTap.numberOfTapsRequired=1;//点击次数
            [_content addGestureRecognizer:singleTap];//添加点击事件
            [singleTap release];
            
            //双击事件
            UITapGestureRecognizer *doubleTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doubleTap:)];
            [_content addGestureRecognizer:doubleTap];
            doubleTap.numberOfTapsRequired=2;//点击次数
            [doubleTap release];
            
            [singleTap requireGestureRecognizerToFail:doubleTap];//因为有冲突，所以要设置双击手势确定监测失败才会触发单击手势的相应操作
            
            //长按事件
//            UILongPressGestureRecognizer *press=[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(press:)];
//            [_content addGestureRecognizer:press];
//            [press release];
            
            //捏合事件
            UIPinchGestureRecognizer *pinch=[[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(pinch:)];
            [_content addGestureRecognizer:pinch];
            [pinch release];
            
            //拖动事件
            UIPanGestureRecognizer *pan=[[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
            [_content addGestureRecognizer:pan];
            [pan release];
            
            
            //是否可以保存
            if(_canSave)
            {
                [self addSubview:_saveButton];
            }
            else
            {
                [_saveButton removeFromSuperview];
            }
            
            
            //添加到窗口
            [[KATAppUtil keyWindow] addSubview:self];
            
            _isShown=YES;
            _animating=YES;
            
            _imageSize=CGSizeMake(image.source.size.width/SCREEN_SCALE, image.source.size.height/SCREEN_SCALE);//图片尺寸
            
            if(_imageSize.width/SCREEN_WIDTH>=_imageSize.height/SCREEN_HEIGHT)
            {
                _scaleRate=_imageSize.width/SCREEN_WIDTH;
            }
            else
            {
                _scaleRate=_imageSize.height/SCREEN_HEIGHT;
            }
            
            _originalFrame=[KATAppUtil frameInWindowFromView:image];
            _isActualSize=NO;
            
            _shadow.alpha=0.1f;
            _content.frame=_originalFrame;
            _content.alpha=0.1f;
            
            [UIView animateWithDuration:_showDuration animations:^
            {
                _content.center=CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
                
                //根据高宽比缩放
                if(_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height)
                {
                    _content.bounds=CGRectMake(0, 0, self.bounds.size.width, _imageSize.height/_scaleRate);
                }
                else
                {
                    _content.bounds=CGRectMake(0, 0, _imageSize.width/_scaleRate, self.bounds.size.height);
                }
                
                _content.alpha=1.0f;
                _shadow.alpha=1.0f;
            }
            completion:^(BOOL finished)
            {
                _animating=NO;
            }];
        }
    }
}


//隐藏
- (void)hide
{
    if(_isShown && !_animating)
    {
        _isShown=NO;
        _animating=YES;
        
        if(!_isLightStyleStatusBar)
        {
            //变回暗色
            [KATAppUtil setStatusBarDarkStyle];
        }
            
        [UIView animateWithDuration:_showDuration animations:^
        {
            _shadow.alpha=0.1f;
            _content.frame=_originalFrame;
            _content.alpha=0.1f;
        }
        completion:^(BOOL finished)
        {
            _animating=NO;
            
            [self removeFromSuperview];
        }];
    }
}


//双击事件
- (void)doubleTap:(UITapGestureRecognizer *)recognizer
{
    if([recognizer view]==self.content)//事件来源是图片控件
    {
        if(!_isActualSize)
        {
            if(!_animating && _isShown)
            {
                _isActualSize=YES;
                _animating=YES;
                
                [UIView animateWithDuration:_showDuration animations:^
                {
                    _content.center=CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
                    
                    _content.bounds=CGRectMake(0, 0, _imageSize.width, _imageSize.height);
                }
                completion:^(BOOL finished)
                {
                    _animating=NO;
                }];
            }
        }
        else
        {
            if(!_animating && _isShown)
            {
                _isActualSize=NO;
                _animating=YES;
                
                [UIView animateWithDuration:_showDuration animations:^
                {
                    _content.center=CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
                    
                    //根据高宽比缩放
                    if(_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height)
                    {
                        _content.bounds=CGRectMake(0, 0, self.bounds.size.width, _imageSize.height/_scaleRate);
                    }
                    else
                    {
                        _content.bounds=CGRectMake(0, 0, _imageSize.width/_scaleRate, self.bounds.size.height);
                    }
                    _content.bounds=self.bounds;
                }
                completion:^(BOOL finished)
                {
                    _animating=NO;
                }];
            }
        }
    }
}


//捏合事件
- (void)pinch:(UIPinchGestureRecognizer *)recognizer
{
    if([recognizer view]==self.content)//事件来源是图片控件
    {
        if(!_animating && _isShown)
        {
            if(recognizer.state==UIGestureRecognizerStateBegan)//开始
            {
                _currentSize=_content.bounds.size;
                
//                _content.center=CGPointMake(self.bounds.size.width/2.0, self.bounds.size.height/2.0);
            }
            else if(recognizer.state==UIGestureRecognizerStateChanged)//改变状态
            {
                //捏合手势中scale属性记录的缩放比例
                _content.layer.bounds=CGRectMake(0, 0, _currentSize.width*recognizer.scale, _currentSize.height*recognizer.scale);
            }
            else if(recognizer.state==UIGestureRecognizerStateEnded)//结束后，超出边界则恢复状态
            {
                BOOL needResize=NO;
                CGRect bounds=_content.bounds;
                
                if(_scaleRate>1.0)
                {
                    if((_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height && _content.bounds.size.width>_imageSize.width) || (_imageSize.width/self.bounds.size.width<_imageSize.height/self.bounds.size.height && _content.bounds.size.height>_imageSize.height))//超出最大值
                    {
                        bounds=CGRectMake(0, 0, _imageSize.width, _imageSize.height);
                        
                        _isActualSize=YES;
                        needResize=YES;
                    }
                    else if((_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height && _content.bounds.size.width<self.bounds.size.width) || (_imageSize.width/self.bounds.size.width<_imageSize.height/self.bounds.size.height && _content.bounds.size.height<self.bounds.size.height))//比最小值小
                    {
                        //根据高宽比缩放
                        if(_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height)
                        {
                            bounds=CGRectMake(0, 0, self.bounds.size.width, _imageSize.height/_scaleRate);
                        }
                        else
                        {
                            bounds=CGRectMake(0, 0, _imageSize.width/_scaleRate, self.bounds.size.height);
                        }
                        
                        _isActualSize=NO;
                        needResize=YES;
                    }
                    else
                    {
                        _isActualSize=NO;
                        needResize=NO;
                    }
                }
                else
                {
                    if((_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height && _content.bounds.size.width>self.bounds.size.width) || (_imageSize.width/self.bounds.size.width<_imageSize.height/self.bounds.size.height && _content.bounds.size.height>self.bounds.size.height))//超出最大值
                    {
                        //根据高宽比缩放
                        if(_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height)
                        {
                            bounds=CGRectMake(0, 0, self.bounds.size.width, _imageSize.height/_scaleRate);
                        }
                        else
                        {
                            bounds=CGRectMake(0, 0, _imageSize.width/_scaleRate, self.bounds.size.height);
                        }
                        
                        _isActualSize=NO;
                        needResize=YES;
                    }
                    else if((_imageSize.width/self.bounds.size.width>=_imageSize.height/self.bounds.size.height && _content.bounds.size.width<_imageSize.width) || (_imageSize.width/self.bounds.size.width<_imageSize.height/self.bounds.size.height && _content.bounds.size.height<_imageSize.height))//比最小值小
                    {
                        bounds=CGRectMake(0, 0, _imageSize.width, _imageSize.height);
                        
                        _isActualSize=YES;
                        needResize=YES;
                    }
                    else
                    {
                        _isActualSize=NO;
                        needResize=NO;
                    }
                }
                
                if(needResize)
                {
                    _animating=YES;
                    
                    [UIView animateWithDuration:_showDuration animations:^
                    {
                        _content.bounds=bounds;
                    }
                    completion:^(BOOL finished)
                    {
                        _animating=NO;
                    }];
                }
                
            }
        }
    }
}


//拖动事件
- (void)pan:(UIPanGestureRecognizer *)recognizer
{
    if([recognizer view]==self.content)//事件来源是图片控件
    {
        if(!_animating && _isShown)
        {
            if(recognizer.state==UIGestureRecognizerStateBegan)//开始
            {
                _currentCenter=_content.center;
            }
            else if(recognizer.state==UIGestureRecognizerStateChanged)//改变状态
            {
                CGPoint translation=[recognizer translationInView:self];
                
                _content.center=CGPointMake(_currentCenter.x+translation.x, _currentCenter.y+translation.y);
            }
            else if(recognizer.state==UIGestureRecognizerStateEnded)//结束后，超出边界则恢复状态
            {
                BOOL needMove=NO;
                float x=_content.center.x;
                float y=_content.center.y;
                
                if(_content.bounds.size.width<=self.bounds.size.width)
                {
                    if(_content.center.x<_content.bounds.size.width/2.0)
                    {
                        x=_content.bounds.size.width/2.0;
                        
                        needMove=YES;
                    }
                    else if(_content.center.x>self.bounds.size.width-_content.bounds.size.width/2.0)
                    {
                        x=self.bounds.size.width-_content.bounds.size.width/2.0;
                        
                        needMove=YES;
                    }
                }
                
                if(_content.bounds.size.height<=self.bounds.size.height)
                {
                
                    if(_content.center.y<_content.bounds.size.height/2.0)
                    {
                        y=_content.bounds.size.height/2.0;
                        
                        needMove=YES;
                    }
                    else if(_content.center.y>self.bounds.size.height-_content.bounds.size.height/2.0)
                    {
                        y=self.bounds.size.height-_content.bounds.size.height/2.0;
                        
                        needMove=YES;
                    }
                }
                
                if(_content.bounds.size.width>self.bounds.size.width)
                {
                    if(_content.center.x>_content.bounds.size.width/2.0)
                    {
                        x=_content.bounds.size.width/2.0;
                        
                        needMove=YES;
                    }
                    else if(_content.center.x<self.bounds.size.width-_content.bounds.size.width/2.0)
                    {
                        x=self.bounds.size.width-_content.bounds.size.width/2.0;
                        
                        needMove=YES;
                    }
                }
                
                if(_content.bounds.size.height>self.bounds.size.height)
                {
                    if(_content.center.y>_content.bounds.size.height/2.0)
                    {
                        y=_content.bounds.size.height/2.0;
                        
                        needMove=YES;
                    }
                    else if(_content.center.y<self.bounds.size.height-_content.bounds.size.height/2.0)
                    {
                        y=self.bounds.size.height-_content.bounds.size.height/2.0;
                        
                        needMove=YES;
                    }
                }
                
                if(needMove)
                {
                    _animating=YES;
                    
                    [UIView animateWithDuration:_showDuration animations:^
                    {
                        _content.center=CGPointMake(x, y);
                    }
                    completion:^(BOOL finished)
                    {
                        _animating=NO;
                    }];
                }
            }
        }
    }
}


//长按事件
- (void)press:(UILongPressGestureRecognizer *)recognizer
{
    if(recognizer.state==UIGestureRecognizerStateBegan)
    {
        
    }
}


//按钮点击
- (void)clickButton:(KATButton *)button
{
    if(button==_saveButton)
    {
        if(_content && _content.source)
        {
            UIImageWriteToSavedPhotosAlbum(_content.source, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);//保存到相簿
        }
        else
        {
            [[KATToast toastWithButton:KATButtonTypeMultiply] show];
        }
    }
}


//保存相册回调方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if(error)
    {        
        [[KATToast toastWithButton:KATButtonTypeMultiply] show];
    }
    else
    {
        [[KATToast toastWithButton:KATButtonTypeCheck] show];
    }
}




//释放内存
- (void)dealloc
{
    [_shadow release];
    [_content release];
    [_saveButton release];
    
    [super dealloc];
}

@end
